﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.Domain.Repositories;
using Abp.UI;
using Abp.Web.Models;
using com.sf.csim.express.service;
using Magicodes.Admin.Authorization;
using Magicodes.Admin.Configuration;
using Magicodes.Admin.SFOrders;
using Magicodes.Admin.SFOrders.Dto;
using Magicodes.Admin.Web;
using Magicodes.Admin.Web.Controllers;
using Magicodes.Admin.WULINGAddresss;
using Magicodes.Admin.WULINGAddresss.Dto;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Magicodes.Admin.Web.Models;
using Castle.Core.Logging;
using Abp.Authorization;
using System.Net;
using System.Collections;
using System.IO;
using System.Text;
using System.Xml;
using Abp.AutoMapper;
using Magicodes.Admin.Custom.Fins;
using Admin.Application.Custom.Fins.Dto;
using Admin.Application.Custom.Fins;

namespace Admin.Host.Controllers
{
    public class FinMonthlyListingController : AdminControllerBase
    {
        private readonly IMonthlyListingAppService _monthlyListingAppService;
        //private readonly IMonthlyListingManager _monthlyListingManager;

        private readonly ILogger _logger;

        public FinMonthlyListingController(
            //IMonthlyListingManager monthlyListingManager,
            IMonthlyListingAppService monthlyListingAppService,
           ILogger logger,
            IHostingEnvironment env)
        {
            _monthlyListingAppService = monthlyListingAppService;
            //_monthlyListingManager = monthlyListingManager;

            _logger = logger;

            _logger.Info("ctor");
        }

        /// <summary>
        /// 系统下单 导入电子表格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AbpMvcAuthorize(AppPermissions.Pages_Manager_FinMonthlyListing)]
        public async Task<JsonResult> ImportFromExcel()
        {
            try
            {
                var importFile = Request.Form.Files.First();

                //Check input
                if (importFile == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                if (importFile.Length > 30720 * 1000) //30KB*1000
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                byte[] fileBytes;
                using (var stream = importFile.OpenReadStream())
                {

                    var data = ExcelHelper.ExcelReader(stream);
                    var columns = new List<string> { 
                           "Sequencenumber"
                          ,"Date"
                          ,"WaybillNumber"
                          ,"AreaOfTheOtherParty"
                          ,"CompanyNameOfTheOtherParty"
                          ,"BillingWeight"
                          ,"ProductType"
                          ,"PaymentMethod"
                          ,"Fee"
                          ,"DiscountOrPromotion"
                          ,"AmountPayable"
                          ,"Agent"
                          ,"ValueAddedFee"
                          ,"PlaceOfOrigin"
                          ,"MailingCompanyName"
                          ,"MailingCompanyTelephone"
                          ,"ArrivingArea"
                          ,"ArrivingCustomerName"
                          ,"ArrivingCustomerTelephone"
                          ,"Sender"
                          ,"MailingTime"
                          ,"OriginatingPlaceProvincialName"
                          ,"MailingCompanyAddress"
                          ,"ReceiptManualNumber"
                          ,"ConsignmentContent"
                          ,"ConsignmentQuantity"
                          ,"DeclaredValue"
                          ,"NumberOfPieces"
                          ,"Volume"
                          ,"DestinationProvinceName"
                          ,"Recipient"
                          ,"ReceivingAddress"
                          ,"DispatchEmployeeNumber"
                          ,"ActualWeight"
                          ,"ReturnBillNumber"
                          ,"SignatoryAndRecipient"
                          ,"TimeOfSigningAndReceiving"
                          ,"ReturnRelatedTransportBillNumber"
                          ,"AdditionalField1"
                          ,"AdditionalField2"
                          ,"AdditionalField3"
                          ,"SettlementDate"
                          ,"PaymentNetwork"
                          ,"SubsidiaryCardNumber"
                          ,"Notes"
                          ,"ExpressContent"
                          ,"Country"
                          ,"RegionType"
                          ,"ReservedFields5"
                          ,"Long"
                          ,"Wide"
                          ,"High"
                          ,"SendCityCode"
                          ,"ReceiveCityCode"
                          ,"SendDeptCode"
                          ,"DeliveryDeptCode"
                    };
                    data.Tables[0].Rows.RemoveAt(0);
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(data.Tables[0]);
                    var importList = data.Tables[0].ExcelReaderToEntitys<ImportMonthlyListingDto>(columns);

                    await _monthlyListingAppService.ImportFromExcel(importList.ToList());


                    return Json(new AjaxResponse(new { code = 0, msg = "" }));
                }


            }
            catch (UserFriendlyException ex)
            {
                return Json(new AjaxResponse(new ErrorInfo(ex.Message)));
            }

        }
    }

}